<template>
  <div class="alloc-menu">
    <el-card>
      <template #header>
        <span>分配菜单</span>
      </template>
      <el-tree
        ref="menuTree"
        :data="menus"
        node-key="id"
        :props="{
          children: 'subMenuList',
          label: 'name'
        }"
        :default-checked-keys="checkedKeys"
        show-checkbox
        default-expand-all
      />
      <div style="text-align: center">
        <el-button @click="resetChecked">
          清空
        </el-button>
        <el-button
          type="primary"
          @click="onSave"
        >
          保存
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
import { ElMessage } from 'element-plus'
import { DefineComponent, defineComponent, onBeforeMount, ref } from 'vue'
import { useRouter } from 'vue-router'
import {
  getMenuNodeList,
  allocateRoleMenus,
  getRoleMenus
} from '/@/services/menu'

const menuTree = ref<DefineComponent | null>(null)

const useHandles = (roleId: number) => {
  const router = useRouter()
  const resetChecked = () => {
    (menuTree.value as DefineComponent).setCheckedKeys([])
  }
  const onSave = async () => {
    const menuIdList = (menuTree.value as DefineComponent).getCheckedKeys()
    // 拿到选中节点的数据 id 列表
    // 请求提交保存
    await allocateRoleMenus({
      roleId: roleId,
      menuIdList
    })
    ElMessage.success('操作成功')
    router.back()
  }
  return {
    onSave,
    resetChecked
  }
}
const useInitMenus = (id: number) => {
  const menus = ref([])
  const checkedKeys = ref([])
  const loadMenus = async () => {
    const { data } = await getMenuNodeList()
    menus.value = data.data
  }
  const loadRoleMenus = async () => {
    const { data } = await getRoleMenus(id)
    console.log(data.data)
    getCheckedKeys(data.data)
  }

  const getCheckedKeys = async (roleMenus: []) => {
    roleMenus.forEach((menu: any) => {
      if (menu.selected) {
        // this.checkedKeys.push(menu.id as never)
        checkedKeys.value = [...checkedKeys.value, menu.id] as any
      }
      if (menu.subMenuList) {
        getCheckedKeys(menu.subMenuList)
      }
    })
  }
  onBeforeMount(async () => {
    await loadMenus()
    loadRoleMenus()
  })
  return {
    menus,
    checkedKeys,
    loadMenus,
    loadRoleMenus
  }
}
export default defineComponent({
  name: 'AllocMenu',
  props: {
    roleId: {
      type: [String, Number],
      required: true
    }
  },
  setup (props) {
    return {
      menuTree,
      ...useInitMenus(+props.roleId),
      ...useHandles(+props.roleId)
    }
  }
})
</script>

<style lang="scss" scoped></style>
